package log

import (
	"bytes"
	"runtime"
)

// 日志数据格式化interface
type Formatter interface {
	Format(*Entry, *bytes.Buffer) error
}

// 日志默认字段重定义
type FieldMap map[string]string

func (f FieldMap) get(key string) string {
	if k, ok := f[key]; ok {
		return k
	}
	return key
}

// 自定义调用帧处理函数
type CustomCaller func(frame *runtime.Frame) (function string, file string)

// 用于解决日志默认字段与自定义字段冲突的问题
// 日志默认字段保持不变,自定义字段加上"fields."前缀
func prefixFieldClashes(data Fields, fieldMap FieldMap) {
	timeKey := fieldMap.get(LogKey_Time)
	if val, ok := data[timeKey]; ok {
		data["fields."+timeKey] = val
		delete(data, timeKey)
	}

	levelKey := fieldMap.get(LogKey_Level)
	if val, ok := data[levelKey]; ok {
		data["fields."+levelKey] = val
		delete(data, levelKey)
	}

	msgKey := fieldMap.get(LogKey_Msg)
	if val, ok := data[msgKey]; ok {
		data["fields."+msgKey] = val
		delete(data, msgKey)
	}

	errKey := fieldMap.get(LogKey_Error)
	if val, ok := data[errKey]; ok {
		data["fields."+errKey] = val
		delete(data, errKey)
	}

	fileKey := fieldMap.get(LogKey_File)
	if val, ok := data[fileKey]; ok {
		data["fields."+fileKey] = val
		delete(data, fileKey)
	}

	funcKey := fieldMap.get(LogKey_Func)
	if val, ok := data[funcKey]; ok {
		data["fields."+funcKey] = val
		delete(data, funcKey)
	}
}
